<script setup>

import {ElInput, ElMessage} from "element-plus";
import {onMounted, ref, watch} from "vue";
import http from "@/request/http.js";
import {useRoute} from "vue-router";
import router from "@/router/index.js";
import {ArrowDown, Delete, EditPen, PieChart, Search, Setting, SwitchButton, User, View} from "@element-plus/icons-vue";
//响应式数据
const isScrolled = ref(false);
const searchQuery = ref('');
const isLoggedIn = ref(false);
const avatarMenuVisible = ref(false)
const userInfo = ref({})
const isLikedLoading = ref(false)
const isCollectedLoading = ref(false)
const isShareLoading = ref(false)
const isCommentedLoading = ref(false)
const isCommentLikedLoading = ref(false)
let role = 0;
// 时间格式化工具函数：去除T并转换为"YYYY-MM-DD HH:mm:ss"
const formatDateTime = (dateString) => {
  if (!dateString) return ''; // 处理空值
  // 替换T为空格，截取到秒（去掉可能的毫秒部分）
  return dateString.replace('T', ' ').split('.')[0];
};
//浏览记录
const readeHistoryVisible = ref(false)
//退出登录提示框
const loginOutDialogVisible = ref(false)
// 获取路由参数
const route = useRoute();
// 热门文章
const hotArticles = ref([]);
const getHotArticles = async () => {
  try {
    const resp = await http.post('/article/getHotList', {
      currentPage: 1, pageSize: 10
    });
    if (resp.code === 200) {
      hotArticles.value = resp.data.records;
    }
  } catch (error) {
    ElMessage.error("热门文章获取失败");
  }
};
// 核心：定义article变量（解决报错的关键）
const article = ref({
  title: '',
  username: '',
  publishTime: '',
  viewCount: '',
  likeCount: 0,
  collectCount: 0,
  categoryName: [],
  content: '',
  articleId: '',
  authorDto: { // 作者信息对象（嵌套结构）
    userId: '', // 用户ID
    username: '', // 作者用户名
    avatar: '', // 头像地址
    level: 0, // 等级
    createTime: '', // 创建时间
    articleCount: 0, // 文章数
    codeAge: 0 // 编码年龄
  }
});
const availablePoints = ref(0);
//文章详情获取
const getArticle = async () => {

  try {
    // 从路由参数中获取文章ID
    const articleIdFromRoute = String(route.params.articleId || '');
    console.log("当前文章ID：", articleIdFromRoute);
    if (!articleIdFromRoute) {
      ElMessage.error("文章ID不存在");
      return;
    }
    const resp = await http.get(`/article/getList/${articleIdFromRoute}`)
    console.log("接口返回完整数据：", resp)
    if (resp.code === 200) {
      article.value = resp.data;
      article.value.articleId = resp.data.articleId;
      article.value.content = article.value.content.replace(/\n/g, '<br>');
      await checkCollectStatus(article.value.articleId);
      await checkLikeStatus(article.value.articleId);
      // 同步更新博主信息（从文章数据中获取）
      if (article.value.authorDto) {
        getFansCount(article.value.authorDto.userId);
        checkFollowStatus(article.value.authorDto.userId);
      }
    } else {
      ElMessage.error("文章不存在")
      router.push("/")
    }
  } catch (error) {
    ElMessage.error("文章获取失败");
  }
}
// 获取用户积分
const fetchPointsInfo = async () => {
  try {
    const res = await http.get('/points/info');
    if (res.code === 200) {
      availablePoints.value = res.data.availablePoints || 0;
    }
  } catch (error) {
    console.error('获取积分信息失败', error);
  }
};
//获取用户信息
const getUserInfo = async () => {
  const response = await http.get('/user/userInfo')
  if (response.code === 200) {
    userInfo.value = response.data
  }
}
//退出登录
const loginOut = () => {
  loginOutDialogVisible.value = false
  sessionStorage.removeItem("token")
  sessionStorage.removeItem("isLogged")
  userInfo.value = null
  isLoggedIn.value = false
  ElMessage.success("已退出登录")
}

//互动区域方法
//定义点赞变量
const isLiked = ref(false);
//定义收藏变量
const isCollected = ref(false);

// 1. 查询当前用户是否已点赞该文章
const checkLikeStatus = async (articleId) => {
  const isLogged = sessionStorage.getItem('isLogged') === 'true';
  if (!isLogged || !articleId) {
    isLiked.value = false; // 未登录或无文章ID，默认未点赞
    return;
  }
  try {
    // 调用后端点赞状态接口（与之前定义的Controller接口对应）
    const resp = await http.get(`/interactions/like/status/${articleId}`);
    if (resp.code === 200) {
      isLiked.value = resp.data; // 后端返回true/false，同步到前端状态
    }
  } catch (error) {
    console.error("查询点赞状态失败：", error);
  }
};
//1.点赞
const handleLike = async (articleId) => {
  // 检测登录状态
  const isLogged = sessionStorage.getItem('isLogged') === 'true'
  if (!isLogged) {
    ElMessage.info("请先登录")
    await router.push('/login')
    return
  }
  try {
    isLikedLoading.value = true
    const resp = await http.post('/interactions/likes', {articleId: articleId});
    if (resp.code === 200) {
      const message = resp.data || '';
      const isCancel = message.includes('取消');

      // 更新点赞状态（isLiked已定义）
      isLiked.value = !isCancel;

      // 更新点赞数（确保是数字）
      article.value.likeCount = (article.value.likeCount || 0) + (isCancel ? -1 : 1);

      ElMessage.success(message || '操作成功');
    } else {
      ElMessage.error("点赞失败")
    }
  } catch (error) {
    ElMessage.error("点赞请求发送失败")
  }
  isLikedLoading.value = false
}
// 2. 查询当前用户是否已收藏该文章
const checkCollectStatus = async (articleId) => {
  const isLogged = sessionStorage.getItem('isLogged') === 'true';
  if (!isLogged || !articleId) {
    isCollected.value = false; // 未登录或无文章ID，默认未收藏
    return;
  }
  try {
    // 调用后端收藏状态接口
    const resp = await http.get(`/interactions/collect/status/${articleId}`);
    if (resp.code === 200) {
      isCollected.value = resp.data; // 后端返回true/false，同步到前端状态
    }
  } catch (error) {
    console.error("查询收藏状态失败：", error);
  }
};

// 收藏
const handleCollect = async (articleId) => {
  // 检测登录状态
  const isLogged = sessionStorage.getItem('isLogged') === 'true'
  if (!isLogged) {
    ElMessage.info("请先登录")
    await router.push('/login')
    return
  }
  try {
    isCollectedLoading.value = true
    const resp = await http.post('/interactions/collect', {articleId: articleId})
    if (resp.code === 200) {
      const message = resp.data || '';
      const isCancel = message.includes('取消');

      isCollected.value = !isCancel;

      // 更新点赞数（确保是数字）
      article.value.collectCount = (article.value.collectCount || 0) + (isCancel ? -1 : 1);

      ElMessage.success(message || '操作成功');
    } else {
      ElMessage.error('收藏失败')
    }
  } catch (error) {
    ElMessage.error('收藏请求发送失败')
  }
  isCollectedLoading.value = false
}

//4.分享 获取url
const getShare = async (articleId) => {
  // 检测登录状态
  const isLogged = sessionStorage.getItem('isLogged') === 'true'
  if (!isLogged) {
    ElMessage.info("请先登录")
    router.push('/login')
    return
  }
  try {
    const resp = await http.post('/interactions/getURL', {articleId: articleId})
    if (resp.code === 200) {
      const Url = resp.data
      console.log(resp)
      ElMessage.success('分享链接已获取');
      // 复制链接到剪贴板
      navigator.clipboard.writeText(Url);
      ElMessage.info('链接已复制到剪贴板');
    }
  } catch (error) {
    ElMessage.error('获取分享链接失败');
    console.error(error);
  }
}
// 执行分享（记录分享行为并给作者加积分）
const handleShare = async (articleId) => {
  try {
    isShareLoading.value = true
    const resp = await http.post('/interactions/shareArticle', {
      articleId: articleId // 传递文章ID
    });
    if (resp.code === 200) {
      ElMessage.success('分享成功');
      getShare(articleId);
    } else {
      ElMessage.warning('分享失败');
    }
  } catch (error) {
    ElMessage.error('分享请求失败');
    console.error(error);
  }
  isShareLoading.value = false
};
// 积分兑换文章热度
const handleIncreaseHot = async (articleId, hotValue) => {
  try {
    // 可先获取用户积分信息进行前端校验
    const userInfo = await http.get('/points/info');
    const needPoints = hotValue * 10;
    if (userInfo.data.availablePoints < needPoints) {
      ElMessage.warning('积分不足，无法提升热度');
      return;
    }

    const resp = await http.post('/points/article/increaseHot', {
      articleId: articleId,
      hotValue: hotValue
    });
    if (resp.code === 200) {
      ElMessage.success('热度提升成功');
      // 可刷新文章热度数据
      getArticle();
    } else {
      ElMessage.error(resp.msg || '热度提升失败');
    }
  } catch (error) {
    ElMessage.error('请求失败，请重试');
    console.error(error);
  }
};

//评论
// 新增评论相关响应式数据
const commentContent = ref('');
const comments = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalComments = ref(0);
const replyCommentId = ref(null); // 用于存储被回复的评论ID（初始为null）
const replyContent = ref('');    // 用于存储回复内容
// 获取文章评论列表
const getComments = async () => {
  try {
    const articleId = route.params.articleId;
    if (!articleId) {
      ElMessage.error("文章ID不存在，无法获取评论");
      return;
    }
    const resp = await http.get(`/comments/getComments/${articleId}`, {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    });
    if (resp.code === 200) {
      comments.value = resp.data.records;
      totalComments.value = resp.data.total;
      comments.value.forEach(comment => {
        checkCommentLikeStatus(comment.commentId);
      });
    }
  } catch (error) {
    ElMessage.error("获取评论失败，请稍后重试");
    console.error("评论获取失败：", error);
  }
};

// 发表评论
const publishComment = async () => {
  const isLogged = sessionStorage.getItem('isLogged') === 'true';
  if (!isLogged) {
    ElMessage.info("请先登录")
    router.push('/login').then();
    return;
  }

  const content = replyCommentId.value ? replyContent.value : commentContent.value;
  if (!content.trim()) {
    ElMessage.warning("评论内容不能为空");
    return;
  }

  try {
    isCommentedLoading.value = true
    const articleId = route.params.articleId;
    const resp = await http.post('/comments/', {
      articleId: articleId,
      content: content,
      parentId: replyCommentId.value || null
    });

    if (resp.code === 200) {
      ElMessage.success(replyCommentId.value ? "回复成功" : "评论发表成功");
      // 重置输入
      if (replyCommentId.value) {
        replyCommentId.value = null;
        replyContent.value = '';
      } else {
        commentContent.value = '';
      }
      currentPage.value = 1;
      getComments();
      if (article.value.commentCount !== undefined) {
        article.value.commentCount++;
      }
    }
  } catch (error) {
    ElMessage.error("操作失败，请稍后重试");
    console.error("评论操作失败：", error);
  }
  isCommentedLoading.value = false
};
//点赞状态
const commentLikedStatus = ref({}); // 存储评论点赞状态，格式: {commentId: true/false}

// 评论点赞状态查询
const checkCommentLikeStatus = async (commentId) => {
  const isLogged = sessionStorage.getItem('isLogged') === 'true';
  if (!isLogged || !commentId) {
    commentLikedStatus.value[commentId] = false;
    return;
  }
  try {
    // 调用后端评论点赞状态接口
    const resp = await http.get(`/comments/like/status/${commentId}`);
    if (resp.code === 200) {
      commentLikedStatus.value[commentId] = resp.data; // 后端返回true/false
    }
  } catch (error) {
    console.error("查询评论点赞状态失败：", error);
    commentLikedStatus.value[commentId] = false;
  }
};
// 评论点赞
const likeComment = async (commentId) => {
  const isLogged = sessionStorage.getItem('isLogged') === 'true';
  if (!isLogged) {
    ElMessage.info("请先登录")
    router.push('/login').then();
    return;
  }

  try {
    isCommentLikedLoading.value = true
    const resp = await http.post('/comments/like', {commentId: commentId});
    console.log("前端传递的commentId：", commentId);
    if (resp.code === 200) {
      const message = resp.data || '';
      const isCancel = message.includes('取消');

      // 更新点赞状态
      commentLikedStatus.value[commentId] = !isCancel;

      // 更新点赞数（+1或-1）
      const comment = comments.value.find(c => c.id === commentId);
      if (comment) {
        comment.likeCount = (comment.likeCount || 0) + (isCancel ? -1 : 1);
      }
      getComments();
      ElMessage.success(message);
    } else {
      ElMessage.error("操作失败");
    }
  } catch (error) {
    ElMessage.error("点赞请求发送失败");
    console.error("评论点赞失败：", error);
  }
  isCommentLikedLoading.value = false
};
// 举报评论
const reportComment = async (commentId) => {
  const isLogged = sessionStorage.getItem('isLogged') === 'true';
  if (!isLogged) {
    ElMessage.info("请先登录")
    router.push('/login?redirect=' + encodeURIComponent(route.fullPath));
    return;
  }

  try {
    const resp = await http.post(`/comments/report/${commentId}`);
    if (resp.code === 200) {
      ElMessage.success("举报成功，我们会尽快处理");
    }
  } catch (error) {
    ElMessage.error("举报失败");
    console.error("评论举报失败：", error);
  }
};
// 删除评论（仅作者或管理员可操作）
const deleteComment = async (commentId) => {
  try {
    const resp = await http.delete(`/comments/${commentId}`);
    if (resp.code === 200) {
      ElMessage.success("删除成功");
      getComments(); // 重新加载评论
      if (article.value.commentCount !== undefined) {
        article.value.commentCount--;
      }
    }
  } catch (error) {
    ElMessage.error("删除失败，您没有权限或评论不存在");
    console.error("评论删除失败：", error);
  }
};
//关注
// 关注相关响应式数据
const isFollowing = ref(false); // 是否正在关注
const fansCount = ref(0); // 粉丝数量
const loadingFollow = ref(false); // 关注操作加载状态
// 获取粉丝数量
const getFansCount = async (userId) => {
  if (!userId) return;
  try {
    const resp = await http.get('/follow/getFansCount', {
      params: {userId}
    });
    if (resp.code === 200) {
      fansCount.value = resp.data;
    }
  } catch (error) {
    console.error("获取粉丝数失败：", error);
  }
};
// 检查当前用户是否已关注该作者
const checkFollowStatus = async (authorId) => {
  const isLogged = sessionStorage.getItem('isLogged') === 'true';
  const currentUserId = sessionStorage.getItem('userId');
  if (!isLogged || !authorId) return;
  if (!isLogged || !authorId || currentUserId === authorId.toString()) {
    isFollowing.value = false; // 自己不能关注自己，强制设为未关注
    return;
  }
  try {
    const resp = await http.get(`/follow/checkFollowing/${authorId}`);
    if (resp.code === 200) {
      // 直接使用后端返回的布尔值（true=已关注，false=未关注）
      isFollowing.value = resp.data;
    }
  } catch (error) {
    console.error("检查关注状态失败：", error);
    // 出错时默认设为未关注，避免界面异常
    isFollowing.value = false;
  }
};

// 关注/取消关注切换
const toggleFollow = async () => {
  const isLogged = sessionStorage.getItem('isLogged') === 'true';
  if (!isLogged) {
    router.push(`/login?redirect=${encodeURIComponent(route.fullPath)}`);
    return;
  }

  const authorId = article.value.authorDto?.userId;
  if (!authorId) {
    ElMessage.error("无法获取作者信息");
    return;
  }

  try {
    loadingFollow.value = true;
    // 调用关注/取消关注接口
    const resp = await http.post('/follow/toggle', {
      authorId: authorId // 传递作者ID（FollowDto需要的参数）
    });

    if (resp.code === 200) {
      // 切换关注状态
      isFollowing.value = !isFollowing.value;
      // 更新粉丝数（+1或-1）
      fansCount.value += isFollowing.value ? 1 : -1;
      ElMessage.success(isFollowing.value ? "关注成功" : "取消关注成功");
    } else {
      // 处理后端返回的错误（如“不能关注自己”）
      ElMessage.error(resp.data || "不能关注自己");
    }
  } catch (error) {
    ElMessage.error("操作失败，请稍后重试");
    console.error("关注操作失败：", error);
  } finally {
    loadingFollow.value = false;
  }
};

//===========================历史记录=======================================
const readeHistoryList = ref([])
const searchTitle = ref('')

//向后端获取记录
const getReadeHistory = async () => {
  const resp = await http.get(`/article/readeHistory?title=${searchTitle.value}`)
  if (resp.code === 200) {
    readeHistoryList.value = resp.data
  }
}
//删除记录
const deleteReadeHistory = async () => {
  const resp = await http.delete('/article/readeHistory')
  if (resp.code === 200) {
    ElMessage.success("删除成功");
    await getReadeHistory()
  } else {
    ElMessage.error(resp.msg)
  }
}

onMounted(() => {
  //获取用户是否登录
  let isLogin = sessionStorage.getItem("isLogged")
  isLoggedIn.value = isLogin !== null ? isLogin === "true" : false;
  if (isLoggedIn.value) {
    getUserInfo()
    role = parseInt(sessionStorage.getItem('role'))
  }
  getArticle();
  getComments();
  getHotArticles();
});

// 监听路由参数变化
watch(
    () => route.params.articleId,
    (newId, oldId) => {
      if (newId !== oldId && newId) {
        // 重新加载数据
        article.value = {
          title: '',
          username: '',
          publishTime: '',
          viewCount: '',
          likeCount: 0,
          collectCount: 0,
          categoryName: [],
          content: '',
          articleId: '',
          authorDto: {
            userId: '',
            username: '',
            avatar: '',
            level: 0,
            createTime: '',
            articleCount: 0,
            codeAge: 0
          }
        };
        getArticle(); // 调用已有的获取文章方法
        getComments(); // 重新加载评论
      }
    },
    {immediate: false} // 初始化时执行一次
);

</script>

<template>
  <div class="min-h-screen flex flex-col">
    <header
        class="sticky top-0 z-50 bg-white shadow-md transition-all duration-300"
    >
      <div class="container mx-auto px-4">
        <!-- 主导航栏 -->
        <div class="flex items-center justify-between h-16">
          <!-- Logo -->
          <div class="flex items-center">
            <a class="text-2xl font-bold text-blue-600 flex items-center" href="/">
              <i class="fa fa-code mr-2"></i>
              <span>DevPlatform</span>
            </a>
          </div>

          <!-- 搜索框 -->
          <div class="hidden md:flex items-center flex-1 max-w-xl mx-8">
            <el-input
                v-model="searchQuery"
                class="w-full"
                clearable
                font-bold="font-bold"
                placeholder="搜索文章标题、作者"
                size="large"
                @keydown.enter="router.push({path:'/search',query:{key:searchQuery}})"
            >
              <template #prefix>
                <el-icon>
                  <Search/>
                </el-icon>
              </template>
            </el-input>
          </div>

          <!-- 登录 -->
          <div v-if="!isLoggedIn" class="flex items-end space-x-4">
            <router-link to="/login">
              <a class="text-gray-500 hover:text-blue-600 transition-colors">
                登录
              </a>
            </router-link>
            <router-link to="/register">
              <a class="text-gray-500 hover:text-blue-600 transition-colors">
                注册
              </a>
            </router-link>
          </div>

          <!--头像功能区-->
          <div v-if="isLoggedIn"
               class="avatar-div"
               @mouseenter="avatarMenuVisible=true"
               @mouseleave="avatarMenuVisible=false">
            <el-avatar :src="userInfo.avatar"
                       class="avatar"
                       fit="cover"
                       @click="router.push(`/MyHomePage?userId=${userInfo.userId}`)"
            />
            <span class="text-base ml-5 text-gray-600">您好，{{ userInfo.username }}</span>
            <el-menu v-show="avatarMenuVisible" class="avatar-menu" mode="vertical">
              <el-menu-item @click="router.push('/userInfo')">
                <el-icon>
                  <User/>
                </el-icon>
                <span>个人中心</span>
              </el-menu-item>
              <el-menu-item v-show="role>=3" @click="router.push('/system')">
                <el-icon>
                  <Setting/>
                </el-icon>
                <span>平台管理系统</span>
              </el-menu-item>
              <el-menu-item v-show="role>=2" @click="router.push('/adManagement')">
                <el-icon>
                  <PieChart/>
                </el-icon>
                <span>广告投放</span>
              </el-menu-item>
              <!--              <el-menu-item index="2">-->
              <!--                <el-icon>-->
              <!--                  <Star/>-->
              <!--                </el-icon>-->
              <!--                <span>收藏</span>-->
              <!--              </el-menu-item>-->
              <!--              <el-menu-item index="3">-->
              <!--                <el-icon>-->
              <!--                  <HeartIcon size="20"/>-->
              <!--                </el-icon>-->
              <!--                <span>喜欢</span>-->
              <!--              </el-menu-item>-->
              <el-menu-item @click="readeHistoryVisible=true">
                <el-icon>
                  <View/>
                </el-icon>
                <span>历史记录</span>
              </el-menu-item>
              <el-menu-item @click="loginOutDialogVisible=true">
                <el-icon>
                  <SwitchButton/>
                </el-icon>
                <span>退出登录</span>
              </el-menu-item>
              <el-dialog v-model="loginOutDialogVisible" :modal="true" title="确认退出登录？" width="30%">
                <template #footer>
                  <div class="dialog-footer">
                    <el-button @click="loginOutDialogVisible = false">取消</el-button>
                    <el-button type="danger" @click="loginOut">
                      确认
                    </el-button>
                  </div>
                </template>
              </el-dialog>
            </el-menu>
          </div>

          <!-- 右侧功能区 -->
          <div class="flex items-center space-x-4">
            <button
                class="hidden md:block bg-orange-500 hover:bg-orange-600 text-white px-4 py-2 rounded-md transition-colors"
                @click="router.push('/articleEditor')"
            >
              <i class="fa fa-pencil mr-1"/>
              <el-icon>
                <EditPen/>
              </el-icon>
              发布
            </button>
          </div>
        </div>

      </div>
    </header>

    <!-- 主内容区 -->
    <main class="flex-1 container mx-auto px-4 py-6">
      <div class="flex flex-col lg:flex-row gap-6">
        <!-- 左侧：博主与热门文章 -->
        <div class="lg:w-1/4 space-y-6">
          <!-- 博主信息 -->
          <div class="bg-white rounded-lg shadow-sm p-5">
            <div class="flex flex-col items-center">
              <div @click="router.push(`/MyHomePage?userId=${article.authorDto.userId}`)">
                <img
                    :src="article.authorDto.avatar || 'https://picsum.photos/id/1005/200/200'"
                    alt="博主头像"
                    class="w-16 h-16 rounded-full mb-3 border-2 border-gray-200"
                >
                <h3 class="font-bold text-lg">{{ article.authorDto?.username || '未知作者' }}</h3>
              </div>

              <div class="grid grid-cols-4 gap-2 text-center text-sm">
                <div>
                  <p class="font-bold">{{ article.authorDto.articleCount || 0 }}</p>
                  <p class="text-gray-500">原创</p>
                </div>
                <div>
                  <!-- 显示实时粉丝数 -->
                  <p class="font-bold">{{ fansCount }}</p>
                  <p class="text-gray-500">粉丝</p>
                </div>
                <div>
                  <p class="font-bold">{{ article.authorDto.codeAge || 0 }}</p>
                  <p class="text-gray-500">码龄(年)</p>
                </div>
                <div>
                  <p class="font-bold">{{ article.authorDto.level || 0 }}</p>
                  <p class="text-gray-500">等级</p>
                </div>
              </div>
              <ElButton
                  :loading="loadingFollow"
                  :type="isFollowing ? 'default' : 'primary'"
                  class="mt-4 w-full"
                  size="small"
                  @click="toggleFollow"
              >
                {{ isFollowing ? '已关注' : '关注' }}
              </ElButton>
            </div>
          </div>

          <!-- 热门文章 -->
          <div class="bg-white rounded-lg shadow-sm p-5">
            <h3 class="font-bold mb-4">热门文章</h3>
            <div class="space-y-3">
              <a
                  v-for="(item, idx) in hotArticles"
                  :key="idx"
                  class="block hover:bg-gray-50 p-2 rounded transition-colors"
                  @click="router.push({name:'article',params:{articleId:item.articleId}})"
              >
                <p class="text-sm font-medium mb-1 line-clamp-1">{{ item.title }}</p>
                <p class="text-gray-500 text-xs"><i class="fa fa-eye mr-1"></i>{{ item.view }}</p>
              </a>
            </div>
          </div>
        </div>

        <!-- 右侧：文章内容 -->
        <div class="lg:w-3/4 space-y-6">
          <!-- 文章头部信息 -->
          <div class="bg-white rounded-lg shadow-sm p-6">
            <h1 class="text-2xl font-bold mb-4">{{ article.title }}</h1>
            <div class="flex items-center text-gray-500 text-sm mb-4">
              <span>{{ article.author }}</span>
              <span class="mx-2">|</span>
              <span>{{ formatDateTime(article.publishTime) }}</span>
              <span class="mx-2">|</span>
              <span><i class="fa fa-eye mr-1"></i>浏览量{{ article.viewCount }}</span>
              <span class="mx-2">|</span>
              <span><i class="fa fa-thumbs-up mr-1"></i>点赞数{{ article.likeCount }}</span>
              <span class="mx-2">|</span>
              <span><i class="fa fa-bookmark mr-1"></i>收藏数{{ article.collectCount }}</span>
            </div>
            <div class="flex flex-wrap gap-2">
              <ElTag
                  v-for="tag in article.categories"
                  :key="tag"
                  size="small"
                  type="info"
              >
                {{ tag }}
              </ElTag>
            </div>
          </div>

          <!-- 文章内容 -->
          <div class="bg-white rounded-lg shadow-sm p-6 prose max-w-none">
            <div v-html="article.content"></div>
          </div>

          <!-- 互动区域 -->
          <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex justify-between items-center mb-4">
              <h3 class="font-bold">互动</h3>
              <div class="flex space-x-4">
                <ElButton :loading="isLikedLoading"
                          class="text-gray-500 hover:text-blue-600"
                          type="text"
                          @click="handleLike(article.articleId)"
                >
                  <i class="fa fa-thumbs-up mr-1"></i>{{ isLiked ? '已点赞' : '点赞' }}
                </ElButton>
                <ElButton class="text-gray-500 hover:text-blue-600" type="text"
                          :loading="isCollectedLoading" @click="handleCollect(article.articleId)">
                  <i class="fa fa-bookmark mr-1"></i>{{ isCollected ? '已收藏' : '收藏' }}
                </ElButton>
                <ElButton :loading="isShareLoading" class="text-gray-500 hover:text-blue-600"
                          type="text" @click="handleShare(article.articleId)">
                  <i class="fa fa-share-alt mr-1"></i>分享
                </ElButton>
                <!-- 积分兑换热度 -->
                <ElDropdown @command="(val) => handleIncreaseHot(article.articleId, val)">
                  <ElButton type="primary">
                    提升热度
                    <ElIcon class="ml-1">
                      <ArrowDown/>
                    </ElIcon>
                  </ElButton>
                  <template #dropdown>
                    <ElDropdownMenu>
                      <ElDropdownItem command="5">5点热度（50积分）</ElDropdownItem>
                      <ElDropdownItem command="10">10点热度（100积分）</ElDropdownItem>
                      <ElDropdownItem command="20">20点热度（200积分）</ElDropdownItem>
                    </ElDropdownMenu>
                  </template>
                </ElDropdown>
              </div>
            </div>
            <div class="bg-white rounded-lg shadow-sm p-6">
              <!-- 评论标题与总数 -->
              <h3 class="font-bold text-lg mb-4">评论区 ({{ totalComments }})</h3>

              <!-- 发表评论输入框 -->
              <div class="mb-6 border-b pb-6">
                <ElInput
                    v-model="commentContent"
                    :rows="3"
                    class="w-full mb-4"
                    clearable
                    placeholder="写下你的看法..."
                    type="textarea"
                ></ElInput>
                <ElButton :loading="isCommentedLoading" size="small" type="primary" @click="publishComment">发布评论
                </ElButton>
              </div>

              <!-- 评论列表（仅一级评论） -->
              <div v-if="comments.length > 0" class="space-y-6">
                <div v-for="(comment, index) in comments" :key="comment.commentId" class="border-b pb-6 last:border-0">
                  <div class="flex items-start">
                    <!-- 评论者头像 -->
                    <img
                        :src="comment.avatar || 'https://picsum.photos/id/1005/40/40'"
                        alt="评论者头像"
                        class="w-10 h-10 rounded-full mr-3 object-cover"
                        @click="router.push(`/MyHomePage?userId=${comment.userId}`)"
                    >
                    <!-- 评论内容与操作 -->
                    <div class="flex-1">
                      <!-- 评论者信息与时间 -->
                      <div class="flex justify-between items-center mb-2">
                        <span class="font-medium text-gray-900">{{ comment.username }}</span>
                        <span class="text-gray-500 text-sm">{{ formatDateTime(comment.commentTime) }}</span>
                      </div>
                      <!-- 评论内容 -->
                      <p class="text-gray-800 mb-3">{{ comment.commentContent }}</p>
                      <!-- 评论操作（点赞/举报/删除） -->
                      <div class="flex items-center text-sm text-gray-500">
                        <!-- 点赞 -->
                        <ElButton
                            class="hover:text-blue-600 transition-colors mr-6"
                            @click="likeComment(comment.commentId)"
                            :loading="isCommentLikedLoading"
                        >
                          <i :class="{ 'text-blue-600': commentLikedStatus[comment.commentId] }"
                             class="fa fa-thumbs-up mr-1"></i>
                          <span>{{
                              commentLikedStatus[comment.commentId] ? '已点赞' : '点赞'
                            }} ({{ comment.likeCount || 0 }})</span>
                        </ElButton>
                        <!-- 举报（弹窗确认） -->
                        <ElPopconfirm
                            cancel-button-text="取消"
                            confirm-button-text="确认"
                            title="确定要举报这条评论吗？"
                            @confirm="reportComment(comment.commentId)"
                        >
                          <template #reference>
                            <button class="hover:text-orange-600 transition-colors mr-6">
                              <i class="fa fa-flag mr-1"></i>举报
                            </button>
                          </template>
                        </ElPopconfirm>
                        <!-- 删除（仅评论作者/管理员可见，需后端返回isOwner字段） -->
                        <ElPopconfirm
                            v-if="comment.isOwner"
                            cancel-button-text="取消"
                            confirm-button-text="确认"
                            title="确定要删除这条评论吗？"
                            @confirm="deleteComment(comment.commentId)"
                        >
                          <template #reference>
                            <button class="hover:text-red-600 transition-colors">
                              <i class="fa fa-trash mr-1"></i>删除
                            </button>
                          </template>
                        </ElPopconfirm>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 无评论提示 -->
              <div v-else class="text-center py-8 text-gray-500">
                <i class="fa fa-comment-o text-2xl mb-2"></i>
                <p>还没有评论，快来抢沙发~</p>
              </div>

              <!-- 评论分页（总数大于每页条数时显示） -->
              <div v-if="totalComments > pageSize" class="flex justify-center mt-8">
                <ElPagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[5, 10, 20]"
                    :total="totalComments"
                    layout="total, sizes, prev, pager, next, jumper"
                    @current-change="getComments"
                    @size-change="(size) => { pageSize.value = size; getComments(); }"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部 -->
    <footer class="bg-gray-900 text-white mt-10 py-8">
      <div class="container mx-auto px-4 text-center">
        <p class="text-gray-400 mb-4">© 2025 DevCommunity · 专注技术分享</p>
        <div class="flex justify-center space-x-6">
          <a class="text-gray-400 hover:text-white transition-colors" href="#">关于我们</a>
          <a class="text-gray-400 hover:text-white transition-colors" href="#">联系我们</a>
          <a class="text-gray-400 hover:text-white transition-colors" href="#">隐私政策</a>
        </div>
      </div>
    </footer>
    <!-- 历史记录列表-->
    <el-drawer v-model="readeHistoryVisible" title="历史记录" @close="searchTitle=''" @open="getReadeHistory">
      <div class="reade-history-delete">
        <el-popconfirm
            cancel-button-text="取消"
            confirm-button-text="确认"
            placement="left-end"
            title="删除所有历史记录？"
            @confirm="deleteReadeHistory"
        >
          <template #reference>
            <el-icon>
              <Delete/>
            </el-icon>
          </template>
        </el-popconfirm>
      </div>
      <el-input v-model="searchTitle"
                class="history-search"
                placeholder="请输入文章标题"
                @change="getReadeHistory"
      >
        <template #prepend>
          <el-icon>
            <Search/>
          </el-icon>
        </template>
      </el-input>
      <div v-show="readeHistoryList.length" class="reade-history-list">
        <el-row justify="space-between"
                style="text-align: center;font-weight: bold;margin-bottom: 10px;">
          <el-col :span="17" class="reade-history-list-title">
            <span>标题</span>
          </el-col>
          <el-col :offset="1" :span="6" class="reade-history-list-time" style="text-align: center">
            <span>时间</span>
          </el-col>
        </el-row>
        <el-row
            v-for="(item,index) in readeHistoryList"
            class="reade-history-list-item"
            justify="space-between"
            @click="router.push({name:'article',params:{articleId:item.articleId}})"
        >
          <el-col :span="17" class="reade-history-list-title">
            {{ item.title }}
          </el-col>
          <el-col :offset="1" :span="6" class="reade-history-list-time">
            {{ formatDateTime(item.readTime) }}
          </el-col>
        </el-row>
      </div>
      <div v-show="!readeHistoryList.length">
        <p style="color: #999;text-align: center;margin-top: 30px">
          暂时没有记录哦~
        </p>
      </div>

    </el-drawer>
  </div>
</template>

<style scoped>
.prose {
  max-width: 100% !important; /* 修复文章内容宽度限制 */
}

.prose img {
  max-width: 100%;
  height: auto;
}

/* 评论操作按钮间距优化 */
button {
  cursor: pointer;
}

/*头像菜单样式*/
.avatar-div {
  display: inline-block;
  position: relative;
  padding: 8px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 20px
}

.avatar-menu {
  position: absolute;
  background-color: white;
  width: 130px;
  top: 100%;
  left: 0;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  animation: fadeIn 0.2s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.avatar-menu span {
  font-size: 12px;
}

/*历史记录样式*/
.reade-history-list {
  overflow: auto;
  font-size: 15px;
}

.reade-history-delete {
  width: 100%;
  display: flex;
  justify-content: end;
  transition: all 0.3s ease;
}

.reade-history-delete:hover {
  color: #ec1717;
}

.history-search {
  margin: 10px 0;
}

.history-search :deep(.el-input-group__prepend) {
  background-color: white;
  padding: 5px 15px;
}

.reade-history-list-item {
  width: 95%;
  left: 8px;
  overflow: visible;
  margin-bottom: 5px;
  transition: all 0.3s ease;
}

.reade-history-list-item:hover {
  transform: scale(1.02);
}

.reade-history-list-time {
  text-align: end;
}

.reade-history-list-title {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏超出容器的内容 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
}
</style>